from constants import *
from base import *
from dict import RimeDict


def build_single_aux(source, target, code_map: dict = None):
    if is_file_exists(target):
        return
    auxDict = RimeDict(source)
    auxDict.load()
    with open_file_as_utf8(SINGLE_LITE_SET) as f:
        with create_utf8_file(target) as out:
            out.write('# 单字辅助码\n')
            for line in f:
                if line.startswith('#'):
                    continue
                text = line.split('\t', maxsplit=2)[0].strip()
                code = None
                if auxDict.hasText(text):
                    aux = auxDict.getItem(text).code
                    code = aux if len(aux) < 4 else aux[0:2] + aux[-2:]
                if code is None:
                    print('{} not found!'.format(text))
                else:
                    out.write('{}\t'.format(text))
                    if code_map is None or len(code_map) == 0:
                        out.write(code)
                    else:
                        for ch in code:
                            if ch in code_map:
                                out.write(code_map.get(ch))
                            else:
                                out.write(ch)
                    out.write('\n')
                    out.flush()


def compose_aux(aux1, aux2, target, code_map: dict = None):
    """
    组合两种编码作为辅助码
    """
    if is_file_exists(target):
        return
    aux1Dict = RimeDict(aux1)
    aux1Dict.load()
    aux2Dict = RimeDict(aux2)
    aux2Dict.load()
    with open_file_as_utf8(SINGLE_LITE_SET) as f:
        with create_utf8_file(target) as out:
            out.write('# 单字辅助码\n')
            for line in f:
                if line.startswith('#'):
                    continue
                text = line.split('\t', maxsplit=2)[0].strip()
                code = None
                if aux1Dict.hasText(text):
                    code1 = aux1Dict.getItem(text).code
                    code = code1[0]
                if code is None:
                    print('{} not found in aux1: {}!'.format(text, aux1))
                    continue
                if aux2Dict.hasText(text):
                    code += aux2Dict.getItem(text).code
                out.write('{}\t'.format(text))
                if code_map is None or len(code_map) == 0:
                    out.write(code)
                else:
                    for ch in code:
                        if ch in code_map:
                            out.write(code_map.get(ch))
                        else:
                            out.write(ch)
                out.write('\n')
                out.flush()
